<template>
  <div ref="imageWrapper">
    <div class="modelTitle"><h2>工程项目实际盈亏模型</h2></div>
    <a-card title="查询条件" class="search">
      <!-- 查询区域 -->
      <div class="table-page-search-wrapper">
        <a-form-model
          ref="ruleForm"
          :model="queryParam"
          :rules="rules"
          layout="inline"
          @keyup.enter.native="searchQuery"
        >
          <a-row :gutter="24">
            <a-col :md="6" :sm="8">
              <a-form-model-item label="审计单位" prop="orgName">
                <a-input v-model="queryParam.orgName" readOnly placeholder="请选择" @click.native="openOrganModel" />
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="6">
              <a-form-model-item label="审计时间" prop="arrayTime">
                <a-range-picker
                  v-model="queryParam.arrayTime"
                  format="yyyy-MM-DD"
                  value-format="yyyy-MM-DD"
                  @change="handleDatechange"
                />
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="6">
              <span style="float: right" class="table-page-search-submitButtons">
                <a-button type="primary" @click="searchQuery" icon="search" class="yellow_search_btn">查询</a-button>
                <a-button @click="searchReset" icon="reload" class="clear_btn">清除条件</a-button>
                <a-button
                  type="danger"
                  :loading="ydLoading"
                  icon="arrow-right"
                  style="margin-left: 18px"
                  @click="handleToYD(false)"
                  >转疑点</a-button
                >
              </span>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
    </a-card>
    <a-card style="margin-top: 20px" v-if="dataSource.length > 0">
      <a-table
        :columns="columns"
        :data-source="dataSource"
        rowKey="line_num"
        :pagination="false"
        :loading="loading"
        :scroll="{ x: aotuScrollX }"
        :row-selection="rowSelection"
        class="antableClass"
      >
        <template slot="title">
          单位：万元
        </template>
        <div slot="customTitle" style="position: relative">
          <div style="position: absolute; top: 14px; left: -55px">项目</div>
          <div style="position: absolute; top: -11px; left: 46px; width: 30px">年度</div>
          <div
            style="
              content: '';
              position: absolute;
              width: 1px;
              height: 167px;
              top: -74px;
              left: 0px;
              background-color: rgb(200 207 211);
              display: block;
              transform: rotate(-71deg);
              box-sizing: border-box;
            "
          ></div>
        </div>
        <template v-for="{ dataIndex } in columns" v-slot:[dataIndex]="text, record">
          <a
            v-if="dataIndex != 'name' && noClickLineNum.indexOf(record.line_num) == -1"
            :key="dataIndex"
            @click="handlerCheckDeatil(text, record)"
          >
            {{ text }}
          </a>
          <span :key="dataIndex" v-else>{{text}}</span>
        </template>
      </a-table>
      <a-card style="margin-top: 20px" v-if="isEmpty">
        <a-empty />
      </a-card>
    </a-card>

    <AuditDepart ref="AuditDepart" @selectedRow="updateQueryParam" />
    <CheckDetail ref="CheckDetail" />
    <YDModel ref="YDModel" :router-data="$route.path" />
  </div>
</template>

<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { getAction, postAction } from '@/api/manage'
import AuditDepart from '@/views/sj/sjmxgl/cwzb/components/AuditDepart'
import { beforeyearYMD, currentYMD } from '@/mixins/commontime.js'
import columns from './columns'
import YDModel from './YDModel'
import { base64toImg } from '@/mixins/base64toImg'
import CheckDetail from '@/views/sj/sjmxgl/cwzb/gcxmsjykd/CheckDetail'
import html2canvas from 'html2canvas'
export default {
  mixins: [JeecgListMixin, base64toImg],
  components: { AuditDepart, YDModel, CheckDetail },
  watch: {
    $route: {
      handler: function(to) {
        if (Object.keys(to.query).length) {
          this.disableMixinCreated = true
          console.log(to.query)
          this.selectedRowKeys = to.query.selectedRowKeys.split(',').map(item => parseInt(item)) || []
          to.query.selectedRowKeys && delete to.query.selectedRowKeys
          this.queryParam = Object.assign(this.queryParam, to.query)
          this.queryParam.arrayTime = to.query.arrayTime.split(',')
          this.$nextTick(() => {
            this.searchQuery()
          })
        }
      },
      immediate: true
    }
  },
  data() {
    return {
      queryParam: {
        orgId: '',
        orgName: '',
        endTime: currentYMD(),
        startTime: beforeyearYMD(3, 'years'),
        arrayTime: [beforeyearYMD(3, 'years'), currentYMD()]
      },
      superParam: {
        id: '67e29f69f20b43ace3e578edbb6bccf8',
        modelId: '67e29f69f20b43ace3e578edbb6bccf8',
        extraFlag: true
      },
      url: {
        list: '/sjmx/queryProfitDef',
        // 查询模型转疑点信息(多选)
        TurnSuspects: '/sjmx/queryModelMsgMulti'
      },
      columns: columns(),
      disableMixinCreated: true,
      dataSource: [],
      rules: {
        orgName: [{ required: true, message: '请选择审计单位' }],
        arrayTime: [{ required: true, message: '请选择审计时间' }]
      },
      isEmpty: false,
      selectedRowKeys: [],
      noClickLineNum: [6, 11, 17, 20, 22]
    }
  },
  computed: {
    aotuScrollX() {
      return (this.columns.length - 10) * 130 + 1000
    },
    // 行选择
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          console.log(selectedRowKeys)
          this.selectedRowKeys = [...selectedRowKeys]
          this.selectedRows = [...selectedRows]
        }
      }
    }
  },
  methods: {
    searchReset() {
      this.queryParam = this.$options.data().queryParam
      this.selectedRowKeys = []
      this.dataSource = []
      this.columns = columns()
    },
    updateQueryParam(checkRow) {
      console.log(checkRow)
      this.queryParam.orgName = checkRow.departName
      this.queryParam.orgId = checkRow.id
    },
    openOrganModel() {
      this.$refs.AuditDepart.show()
    },
    handleDatechange(dates) {
      this.queryParam.startTime = dates[0]
      this.queryParam.endTime = dates[1]
    },
    handleOk(checkRow, keyStr) {
      this.queryParam.accName = checkRow[0].title
      this.queryParam.unitId = keyStr
      console.log(checkRow, keyStr)
    },
    handlerCheckDeatil(text, record) {
      // 点击跳转
      if (Number(text) === 0) {
        this.$message.warning('无当前数据')
      } else {
        let key = Object.keys(record).find(item => {
          if (record[item] == text) return item
        })
        let year = `${key.substring(0, 4)}-01-01`
        let params = Object.assign({}, this.queryParam)
        if (record.line_num == 9) {
          params.direction = -1
        } else if (record.line_num == 10) {
          params.direction = 1
        }
        this.$refs.CheckDetail.edit(params, record, year)
      }
    },
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      // 加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      var params = this.getQueryParams() // 查询条件
      this.loading = true
      this.columns = columns()
      // this.dataSource=[]
      getAction(this.url.list, params).then(res => {
        if (res.success) {
          this.dataSource = res.result.records || res.result
          let row = this.dataSource[0]
          if (row) {
            let rowsKeys = Object.keys(row).reverse()
            rowsKeys.map((item, index) => {
              if (item != 'line_num' && item != 'name' && item != 'total') {
                this.columns.splice(this.columns.length - 1, 0, {
                  title: item,
                  dataIndex: `${item}`,
                  align: 'center',
                  key: `${index + 1}`,
                  scopedSlots: { customRender: `${item}` }
                })
              }
            })
          } else {
            this.isEmpty = true
          }

          if (res.result.total) {
            this.ipagination.total = res.result.total
          } else {
            this.ipagination.total = 0
          }
        } else {
          this.$message.error(res.message)
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        this.loading = false
      })
    },
    handleToYD(record) {
      if (this.dataSource.length) {
        const { startTime = '', endTime = '' } = this.queryParam
        let param = Object.assign({}, this.queryParam, {
          selectedRowKeys: this.selectedRowKeys.join(',')
        })
        let ydnr = undefined
        let gzzd = undefined
        // if (record) {
        //   ydnr = `【科目代码：${record.subjectCode}】【科目名称：${record.subjectName}】`
        // }
        let time = `【${startTime}～${endTime}】【工程项目实际盈亏模型】`
        this.addYd(param, ydnr, time, gzzd)

        let ydList = JSON.stringify(this.selectedRows)
        postAction(this.url.TurnSuspects, Object.assign({}, this.queryParam, this.superParam, { ydList: ydList })).then(
          res => {
            if (res.success) {
              if (res.result.length) {
                ydnr = res.result[0].ydms ? res.result[0].ydms : ydnr
                gzzd = res.result[0].gzzd ? res.result[0].gzzd : gzzd
              }
              this.addYdMulti(param, ydnr, time, gzzd)
            } else {
              this.$message.error(res.message)
            }
            if (res.code === 510) {
              this.$message.warning(res.message)
            }
          }
        )
      } else {
        this.$message.error('空数据不能新建疑点')
      }
    },
    addYd(record, ydnr, time, gzzd) {
      this.ydLoading = true
      html2canvas(this.$refs.imageWrapper).then(canvas => {
        let dataURL = canvas.toDataURL('image/png')
        console.log('父组件调用完了')
        this.$refs.YDModel.show(record, dataURL, ydnr, time, gzzd)
        this.ydLoading = false
      })
    }
  }
}
</script>
<style lang="less">
.bgc_tooltip {
  .ant-tooltip-inner {
    // 这里是框框
    border-radius: 20px;
    color: #333;
    width: 400px;
    padding: 10px 15px;
    background-color: rgba(255, 255, 255, 0.8) !important;
  }

  .ant-tooltip-arrow::before {
    // 这里是小三角形
    background-color: #fff !important;
  }
}
</style>
<style lang="less" scoped>
@import '~@assets/less/tableTheme.less';

.ant-table-fixed-left .ant-table-thead > tr > th:last-child {
  border-top-right-radius: 0;
  background-color: red;
  padding: 0;
}
.antableClass {
  /deep/.ant-table-thead tr th {
    text-align: center !important;
  }
}
.modelTitle {
  display: flex;
  justify-content: center;
  align-items: center;
  h2 {
    font-weight: 600;
  }
}
</style>
